<template>
  <el-dialog
    :title="showTitle"
    :visible.sync="showDialog"
    width="45%"
    @close="btnCancel"
  >
    <!-- 匿名插槽 -->
    <el-form ref="deptForm" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="getEmployeesSimple">
          <!-- 循环渲染人名 -->
          <el-option v-for="item in peoples" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="btnCancel">取消</el-button>
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
      </el-col>

    </el-row>
  </el-dialog>

</template>
<script>
import { getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeesSimple } from '@/api/employees'
const defaultItem = {
  name: '',
  code: '',
  manager: '',
  introduce: ''
}
export default {
  name: 'AddDepts',
  components: {},
  props: {
    // 当前操作的节点
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    // 去找同级部门是否有重名
    const checkNameRepeat = async(rules, value, callback) => {
      // 1.找到部门数据
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // 2.找到父亲的儿子 去判断是否重名
        // 1.有id就是编辑模式
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid && item.id !== this.formData.id).some(item => item.name === value)
      } else {
        // 2.没有id就是新增模式
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
      }

      // 3.返回信息
      isRepeat ? callback(new Error(`同级部门下已经有${value}了`)) : callback()
    }
    const checkCodeRepeat = async(rule, value, callback) => {
      // 先要获取最新的组织架构数据
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        isRepeat = depts.some(item => item.id !== this.formData.id && item.code === value && value) // 这里加一个 value不为空 因为我们的部门有可能没有code
      } else {
        isRepeat = depts.some(item => item.code === value && value) // 这里加一个 value不为空 因为我们的部门有可能没有code
      }
      isRepeat ? callback(new Error(`组织架构中已经有部门使用${value}编码`)) : callback()
    }
    return {
      showDialog: false,
      // 定义一个表单数据
      formData: { ...defaultItem },
      // 获取部门详情
      async getDepartDetail(id) {
        // 请求来的数据回显给表单
        this.formData = await getDepartDetail(id)
      },
      // 校验规则 {key:数组}
      rules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { trigger: 'blur', validator: checkNameRepeat }
        ],
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { trigger: 'blur', validator: checkCodeRepeat }
        ],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      },
      peoples: []
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增子部门'
    }
  },
  watch: {},
  mounted() {},
  methods: {
    async getEmployeesSimple() {
      this.peoples = await getEmployeesSimple()
    },
    // 提交事件
    btnOK() {
      // 1.校验数据
      this.$refs.deptForm.validate(async isOK => {
        if (!isOK) return false
        // 2.发送请求
        if (this.formData.id) { // 判断是否已经有部门id 如果有就是编辑 没有就是新增
          // 编辑请求
          await updateDepartments(this.formData)
        } else {
          // 新增请求
          await addDepartments({
            ...this.formData,
            pid: this.treeNode.id
          })
        }

        // 3.提示成功或失败
        this.$message.success('操作成功')
        // 4.更新列表
        this.$emit('addDepts')
        // 5.重置表单
        this.$refs.deptForm.resetFields()
        // 6.关闭弹框
        this.showDialog = false
      })
    },
    // 取消
    btnCancel() {
      // 1.重置表单
      this.formData = { ...defaultItem }
      this.$refs.deptForm.resetFields()
      // 2.关闭弹框
      this.showDialog = false
    }
  }
}
</script>
<style scoped lang="less">
</style>
